package com.nami.conver.controller.middleware.mq.consumer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONUtil;
import com.google.protobuf.InvalidProtocolBufferException;
import com.nami.conver.facade.grpmsg.GrpConverFacade;
import com.nami.conver.facade.grpmsg.request.GrpConverCmd;
import com.nami.gate.external.basic.constants.ConverTopicConst;
import com.nami.im.network.model.message.v2.Message;
import com.nami.transport.proto.codec.MqTransMsg;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.dromara.common.json.utils.JsonUtils;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = ConverTopicConst.GCHAT_UPD_CONVERS_TOPIC,
    consumerGroup = ConverTopicConst.GCHAT_UPD_CONVERS_CONSUMER_GROUP,
    consumeMode = ConsumeMode.CONCURRENTLY)
public class GrpConverConsumer implements RocketMQListener<MessageExt> {

    private final GrpConverFacade grpConverFacade;

    @Override
    public void onMessage(MessageExt msg) {
        try {
            TimeInterval timer = DateUtil.timer();
            GrpConverCmd cmd = parseGrpConverCmd(msg.getBody());
            grpConverFacade.execute(cmd);
            if (timer.interval() > 200) {
                log.warn("[gconver] 群聊刷新会话超时，senderId={}, recvId={}, msgId={}", JSONUtil.toJsonStr(cmd));
            }
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }

    private GrpConverCmd parseGrpConverCmd(byte[] msg) {
        MqTransMsg.GrpLogic2DispatchBody body;
        try {
            body = MqTransMsg.GrpLogic2DispatchBody.parseFrom(msg);
        } catch (InvalidProtocolBufferException e) {
            throw new RuntimeException(e);
        }
        MqTransMsg.TransUser sender = body.getSender();
        Message downMsg = JsonUtils.parseObject(body.getMessage().toByteArray(), Message.class);

        GrpConverCmd cmd = new GrpConverCmd();
        cmd.setSeq(downMsg.getMsgSeqNo());
        cmd.setSenderId(downMsg.getSenderId());
        cmd.setReceiverId(downMsg.getTargetId());
        cmd.setAppKey(sender.getAppKey());
        cmd.setPayload(downMsg.getMsgContent());
        cmd.setMessageId(downMsg.getMsgId());
        cmd.setTime(downMsg.getMsgTime());

        return cmd;
    }

}
